package com.inet.util;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.activation.MimetypesFileTypeMap;

import org.json.JSONObject;

import android.graphics.Bitmap;
import android.os.Environment;
import android.util.Log;

public class HttpUtil {
	private static int CONNECTION_TIMEOUT_INT = 6000;
	private static int READ_TIMEOUT_INT = 6000;

	private static int postNumber = 0; // post请求次数
	private static int getNumber = 0;  // get请求次数
	
	public static String VideoPath;  //播放视频文件的下载路径

	/**
	 * 通用POST請求
	 * @param paramsMap
	 * @param URL
	 * @return
	 */
	public static String sendPost(Map<String, String> paramsMap, String URL) {
		String result = ""; // 获取服务器返回数据
		StringBuffer buff = new StringBuffer();  // 创建一个空StringBuffer存发给服务器的数据
		// 迭代Map拼接请求参数
		for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
			buff.append(entry.getKey()).append('=').append(entry.getValue())
					.append('&');
		}
		if (buff != null) {
			buff.delete(buff.lastIndexOf("&"), buff.length());
			URL url = null;
			BufferedReader bufferReader = null;
			HttpURLConnection urlConn = null;
			try {
				url = new URL(URL);
				urlConn = (HttpURLConnection) url.openConnection();
				urlConn.setDoInput(true); // 设置输入流采用字节流
				urlConn.setDoOutput(true);// 设置输出流采用字节流
				urlConn.setRequestMethod("POST");
				urlConn.setUseCaches(false); // 设置缓存
				urlConn.setRequestProperty("Charset", "utf-8");
				urlConn.setConnectTimeout(CONNECTION_TIMEOUT_INT);
				urlConn.setReadTimeout(READ_TIMEOUT_INT);

				urlConn.connect(); // 连接既往服务端发送消息

				DataOutputStream dop = new DataOutputStream(
						urlConn.getOutputStream());
				dop.write(buff.toString().getBytes("utf-8")); // 发送参数
				dop.flush(); // 发送，清空缓存
				dop.close(); // 关闭

				int statusCode = urlConn.getResponseCode();
				if (statusCode == 200) {

					// 下面开始做接收工作
					InputStreamReader inputStream = new InputStreamReader(
							urlConn.getInputStream());
					bufferReader = new BufferedReader(inputStream);
					String readLine = null;
					while ((readLine = bufferReader.readLine()) != null) {
						result += readLine;
					}
					inputStream.close();
				} else {
					L.i("sendPost ResponseCode Statuscode ==" + statusCode);
				}
				postNumber = 0;
			} catch (MalformedURLException e) {
				L.i("post MalformedURLException===" + e.toString());
			} catch (IOException e) {
				L.i("post  IOException==" + e.toString());
				postNumber++;
				if (postNumber == 3) {
					postNumber=0;
					return null;
				}
				sendPost(paramsMap, URL);
			} finally {
				if (urlConn != null) {
					urlConn.disconnect();
				}

				if (bufferReader != null) {
					try {
						bufferReader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return result;
	}

	/**
	 * 通用Get請求
	 * @param paramsMap
	 * @param url
	 * @return
	 */
	public static String sendGet(Map<String, String> paramsMap, String url) {

		String getUrl;
		BufferedReader bufferReader = null;
		StringBuffer buff = new StringBuffer();
		buff.append("?");
		for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
			buff.append(entry.getKey() + "=");
			buff.append(entry.getValue());
			buff.append("&");
		}
		getUrl = url + buff.toString();

		L.i("this request get url is " + getUrl);
		String resultStr = "";
		HttpURLConnection urlConnection = null;
		try {
			URL curl = new URL(getUrl);
			urlConnection = (HttpURLConnection) curl.openConnection();
			urlConnection
					.setRequestProperty("Content-Type", "application/json");
			urlConnection.setRequestProperty("Accept", "application/json");
			urlConnection.setRequestMethod("GET");
			urlConnection.setConnectTimeout(CONNECTION_TIMEOUT_INT);
			urlConnection.setReadTimeout(READ_TIMEOUT_INT);
			int statusCode = urlConnection.getResponseCode();
			if (statusCode == 200) {
				L.i("sendGet success");
				InputStreamReader inputStream = new InputStreamReader(
						urlConnection.getInputStream());
				bufferReader = new BufferedReader(inputStream);
				String readLine = null;
				while ((readLine = bufferReader.readLine()) != null) {
					resultStr += readLine;
				}
				inputStream.close();
			} else {
				L.i("sendGet fail");
			}
			getNumber = 0;
		} catch (MalformedURLException e) {
			L.i("post  MalformedURLException==" + e.toString());
		} catch (ProtocolException e) {
			L.i("post  ProtocolException==" + e.toString());
		} catch (IOException e) {
			L.i("post  IOException==" + e.toString());
			getNumber++;
			if (getNumber == 3) {
				getNumber = 0;
				return null;
			}
			sendGet(paramsMap, url);
		} finally {
			if (null != urlConnection)
				urlConnection.disconnect();
			if (null != bufferReader) {
				try {
					bufferReader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return resultStr;
	}
	
	
	/**
	 * 获取二维码所需要的url值
	 * @param json 携带的参数
	 * @param URL 微信二维码获取地址
	 * @return
	 */
	public static String sendQrcodePost(String json, String URL) {
		String result = ""; // 获取服务器返回数据
		L.i("json========="+json);
		if (json != null) {
			URL url = null;
			BufferedReader bufferReader = null;
			HttpURLConnection urlConn = null;
			try {
				url = new URL(URL);
				urlConn = (HttpURLConnection) url.openConnection();
				urlConn.setDoInput(true); // 设置输入流采用字节流
				urlConn.setDoOutput(true); // 设置输出流采用字节流
				urlConn.setRequestMethod("POST");
				urlConn.setUseCaches(false); // 设置缓存
				urlConn.setRequestProperty("Charset", "utf-8");
				urlConn.setConnectTimeout(CONNECTION_TIMEOUT_INT);
				urlConn.setReadTimeout(READ_TIMEOUT_INT);

				urlConn.connect(); // 连接既往服务端发送消息

				DataOutputStream dop = new DataOutputStream(
						urlConn.getOutputStream());
				dop.write(json.toString().getBytes("utf-8")); // 发送参数
				dop.flush(); // 发送，清空缓存
				dop.close(); // 关闭

				int statusCode = urlConn.getResponseCode();
				if (statusCode == 200) {

					// 下面开始做接收工作
					InputStreamReader inputStream = new InputStreamReader(
							urlConn.getInputStream());
					bufferReader = new BufferedReader(inputStream);
					String readLine = null;
					while ((readLine = bufferReader.readLine()) != null) {
						result += readLine;
					}
					inputStream.close();
				} else {
					L.i("sendPost ResponseCode Statuscode ==" + statusCode);
				}
				postNumber = 0;
			} catch (MalformedURLException e) {
				L.i("post MalformedURLException===" + e.toString());
			} catch (IOException e) {
				L.i("post  IOException==" + e.toString());
				postNumber++;
				if (postNumber == 3) {
					postNumber=0;
					return null;
				}
			} finally {
				if (urlConn != null) {
					urlConn.disconnect();
				}

				if (bufferReader != null) {
					try {
						bufferReader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return result;
	}
	
	
	/**
	 * 被动文件上传,(包括图片和视频)-主动获取----------------
	 * @param maps 文件上传需要携带的信息，文件类型，客户编号，openId，imei，位置,时间
	 * @param path 需要上传文件路径
	 */
	public static String activeUploadMedia(Map<String, String> maps,Map<String, String> fileMap,String type,boolean isWarning){
		String res=null;
		String BOUNDARY = "---------------------------123821742118716";// boundary就是request头和上传文件内容的分隔符
		HttpURLConnection conn=null;
		try {
			URL url=null;
			if(isWarning){
				url=new URL(Utils.getPropertiesValue("post_warningUpload"));
			}else{
				url=new URL(Utils.getPropertiesValue("post_activeUploadMedia"));
			}
			L.i("httputil url="+url);
			 conn=(HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(6000);
			conn.setReadTimeout(6000);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
			conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
			
			OutputStream out = new DataOutputStream(conn.getOutputStream());
			// text
			if (maps != null) {
				StringBuffer strBuf = new StringBuffer();
				Iterator iter = maps.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
					strBuf.append(inputValue);
				}
				out.write(strBuf.toString().getBytes());
			}
			
			if (fileMap != null) {
				Iterator iter = fileMap.entrySet().iterator();
				while (iter.hasNext()) {
					Map.Entry entry = (Map.Entry) iter.next();
					String inputName = (String) entry.getKey();
					String inputValue = (String) entry.getValue();
					if (inputValue == null) {
						continue;
					}
					File file = new File(inputValue);
					if(type.equals("getPhoto")){
						
					L.i("file.length="+file.length());
				//add start by xyw 
					byte[] b=BitmapUtils.getByte(file);
					Bitmap bmp=BitmapUtils.loadBitmap(b, 320, 240);
					BitmapUtils.saveFile(bmp, inputValue);
					File file2 = new File(inputValue);
					L.i("file2.length="+file2.length());
			    //add end by xyw 		
					}
					String filename = file.getName();
					String contentType = new MimetypesFileTypeMap().getContentType(file);
					if (filename.endsWith(".png")) {
						contentType = "image/png";
					}
					if (contentType == null || contentType.equals("")) {
						contentType = "application/octet-stream";
					}

					StringBuffer strBuf = new StringBuffer();
					strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
					strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n");
					strBuf.append("Content-Type:" + contentType + "\r\n\r\n");

					out.write(strBuf.toString().getBytes());

					DataInputStream in = new DataInputStream(new FileInputStream(file));
					int bytes = 0;
					byte[] bufferOut = new byte[1024];
					while ((bytes = in.read(bufferOut)) != -1) {
						out.write(bufferOut, 0, bytes);
					}
					in.close();
				}
			}
			
			byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
			out.write(endData);
			out.flush();
			out.close();
			// 读取返回数据
			StringBuffer resBuf = new StringBuffer();
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line = null;
			while ((line = reader.readLine()) != null) {
				resBuf.append(line).append("\n");
			}
			res = resBuf.toString().trim();
			reader.close();
			reader = null;
			
			
		} catch (MalformedURLException e) {
			L.i("HttpUtil:activeUploadMedia--MalformedURLException="+e.toString());
			e.printStackTrace();
		} catch (IOException e) {
			L.i("HttpUtil:activeUploadMedia--IOException="+e.toString());
			e.printStackTrace();
		} catch (Exception e) {
			L.i("HttpUtil:activeUploadMedia--Exception="+e.toString());
			e.printStackTrace();
		}finally{
			conn.disconnect();
		}
		return res;
	}
	
	/**
	 * 下载视频
	 * @param path 下载路径
	 * @return
	 */
	public static synchronized String downloadVideo(String path) {
		VideoPath=path;
		String savePath = Environment.getExternalStorageDirectory()
				+ "/ConsoleservicesVideo/";
		File file = new File(savePath);
		if (!file.exists()) {
			file.mkdir();
		}
		int i = path.lastIndexOf("/");
		String fileName = savePath + path.substring(i + 1);
		// 判断文件是否已经下载
		File f = new File(fileName);
		if (f.exists()) {
			return fileName;
		}
		L.i("fileName" + fileName);
		try {
			// 构造URL
			URL url = new URL(path);
			// 打开连接
			URLConnection con = url.openConnection();
			// 获得文件的长度
			int contentLength = con.getContentLength();
			// 输入流
			InputStream is = con.getInputStream();
			// 1K的数据缓冲
			byte[] bs = new byte[1024];
			// 读取到的数据长度
			int len;
			// 输出的文件流
			OutputStream os = new FileOutputStream(fileName);
			// 开始读取
			L.i("download  start");
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			L.i("download  complete");
			// 完毕，关闭所有链接
			os.close();
			is.close();

			return fileName;
		} catch (Exception e) {
			e.printStackTrace();
			L.i("downloadVideo error=="+e.toString());
		}
		return fileName;
	}
}
